#pragma once

#include <iostream>
#include "sock.hpp"
#include "epoll.hpp"
#include "vector"
static const int defaultport = 8888;
static const int maxevents = 32;
//基于LT水平触发的epoll服务器,目前只关心读事件
class Epollserver{
public:
    Epollserver(int port = defaultport) : _port(defaultport)
    {
        _readylist = new struct epoll_event[maxevents];
    }
    ~Epollserver()
    {
        delete[] _readylist;
    }
public:
    void init(){
        //创建套接字
        _sock.Socket();
        //绑定端口号
        _sock.Bind(_port);
        //将套接字设置为监听状态
        _sock.Listen();
        //创建epoll模型
        _epoll.Create();
        //将监听添加到epoll模型中
        _epoll.AddEvent(_sock.Getsock(),EPOLLIN);
    }
    void start(){
        for(;;){
            int readyeventsnum = _epoll.Wait(_readylist,maxevents);
            //阻塞式的wait，当返回时一定有事件就绪了;
            handler(readyeventsnum);
        }
    }
private:
    void handler(int readynum){
        for(int i = 0 ; i < readynum ;i++){
            //读事件就绪
            struct epoll_event* event = _readylist+i;
            if(event->events & EPOLLIN){
                int fd = event->data.fd;
                
                if(fd == _sock.Getsock()){
                    //监听fd读就绪
                    // logmessage(DEBUG,"")
                    int sockfd = _sock.Accept();
                    _epoll.AddEvent(sockfd,EPOLLIN);
                }else{
                    //普通fd读就绪
                    readhandler(fd);
                }
            }
        }
    }
    void readhandler(int fd){
        char buffer[1024];
        ssize_t s = read(fd,buffer,sizeof(buffer) -1 );
        if( s > 0 ){
            buffer[s-1] = 0;
            std::cout<<"client:"<<buffer<<std::endl;
        }else if ( s == 0 ){
            _epoll.DelEvent(fd);
        }else{
            logmessage(ERROR,"readhandler faild");
        }
    }

private:
    Sock _sock;
    Epoll _epoll;
    int _port;
    struct epoll_event* _readylist;
};